package com.tszs.Controller;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.tszs.bean.Car;
import com.tszs.biz.CommodityListBiz;
import com.tszs.biz.PersonalOrderBiz;
import com.tszs.entity.CommodityList;
import com.tszs.entity.CommodityListExample;
import com.tszs.entity.PersonalOrder;
import com.tszs.entity.PersonalOrderExample;
import com.tszs.entity.PersonalOrderExample.Criteria;
import com.tszs.util.CallBack;
import com.tszs.util.DateUtils;
import com.tszs.util.DoubleUtil;
import com.tszs.util.RandomUtils;
import com.tszs.util.Uuid;

/**
 * @类名：PersonalOrderController
 * @类描述：个人订单表
 * @author 王俊
 * @data 2019-04-20 11:08:08
 *
 */
@Controller
public class PersonalOrderController {
	/**
	 * @PersonalOrderBiz
	 */
	@Autowired
	private PersonalOrderBiz personalOrderBiz;
	/**
	 * @CommodityListBiz
	 */
	@Autowired
	private CommodityListBiz commodityListBiz;
	
	/***
	 * 修改默认收货地址
	 * @author MRC
	 * @date 2019年5月30日下午12:00:01
	 * @param request
	 * @param response
	 */
	@RequestMapping("txr/updateDefault")
	public void updateDefault(HttpServletRequest request,HttpServletResponse response) {
		
		String pId = (String) request.getParameter("cId");
		String address = (String) request.getParameter("address");
		
		PersonalOrder personOrder = new PersonalOrder();
		personOrder.setReceivingAddress(address);
		personOrder.setpStatic("1");//购物车过来的数据变成订单
		
		PersonalOrderExample personExample = new PersonalOrderExample();
		Criteria criteria = personExample.createCriteria();
		criteria.andPIdEqualTo(pId);
		personalOrderBiz.updateByExampleSelective(personOrder, personExample);
		
	}
	/**
	 * @类名：insertOrder
	 * @类描述：首次加入购物车 
	 * @author 王俊
	 * @data 2019-04-20 11:08:08
	 *
	 */
	@RequestMapping("txr/insertOrder")
	public void insertOrder(HttpServletRequest request,HttpServletResponse response) {
		String shopId=request.getParameter("shopId");
		String num=request.getParameter("num");
		String pStatic = request.getParameter("pStatic");
		CommodityList exampleCommodityList=new CommodityList();
		exampleCommodityList.setcId(shopId);
		
		CommodityListExample commodityListExample = new CommodityListExample();
		
		com.tszs.entity.CommodityListExample.Criteria criteria = commodityListExample.createCriteria();
		criteria.andCIdEqualTo(shopId);
		List<CommodityList> findprice=commodityListBiz.selectByExample(commodityListExample);
		
		String cost = findprice.get(0).getcNum();//存放的是成本价
		String price = findprice.get(0).getcPrice();//售价
		
		PersonalOrderExample example=new PersonalOrderExample();
		com.tszs.entity.PersonalOrderExample.Criteria ca=example.createCriteria();
		ca.andUIdEqualTo(request.getSession().getAttribute("openid")+"");
		ca.andProductIdEqualTo(shopId);
		ca.andPStaticEqualTo("0");
		List<PersonalOrder> selectByExample=personalOrderBiz.selectByExample(example);
		PersonalOrder record=new PersonalOrder();
		if(selectByExample.size()>0 && "0".equals(pStatic)) {
			//修改数量
			record.setProductNum(num);
			record.setuName(DoubleUtil.mul(Double.parseDouble(num),Double.parseDouble(cost)).toString());
			record.setTotalCommodityPrice(DoubleUtil.mul(Double.parseDouble(num),Double.parseDouble(price)).toString());
			
			PersonalOrderExample example2=new PersonalOrderExample();
			com.tszs.entity.PersonalOrderExample.Criteria ca2=example2.createCriteria();
			ca2.andPIdEqualTo(selectByExample.get(0).getpId());
			personalOrderBiz.updateByExampleSelective(record, example2);
			List<String>list=new ArrayList<>();			
			list.add(selectByExample.get(0).getpId());
			new CallBack().yes(response, list, "");
		} else {
			//不存在新建
			String pid=Uuid.getUUID();
			record.setpId(pid);
			record.setuId(request.getSession().getAttribute("openid")+"");
			record.setuName(cost);
			record.setTradeno(price);
			record.setTradeno(DateUtils.getNowDatetoString() + RandomUtils.generateNum(20));
			record.setpCreateTime(Uuid.getTime());
			record.setpStatic("0");//购物车商品
			record.setProductId(shopId);//商品iD
			record.setPayStatic("0");
			record.setdDistributionidentification((String)request.getSession().getAttribute("distributionId"));//分销id
			record.setTotalCommodityPrice(price);
			record.setProductNum(num);//数量
			record.setpStatic(pStatic);//0购物车1订单
			personalOrderBiz.insertSelective(record);
			List<String>list=new ArrayList<>();			
			list.add(pid);
			new CallBack().yes(response,list, "");
		}
	}
	/**
	 * @类名：findUidCar
	 * @类描述：个人购物车查询
	 * @author 王俊
	 * @data 2019-04-20 11:08:08
	 *
	 */
	@RequestMapping("txr/findUidCar")
	public void findUidCar(HttpServletRequest request,HttpServletResponse response) {
		PersonalOrderExample example=new PersonalOrderExample();
		Criteria criteria = example.createCriteria();
		
		criteria.andUIdEqualTo(request.getSession().getAttribute("openid")+"");
		criteria.andPStaticEqualTo("0");//表示购物车
		List<PersonalOrder> findUidCar=personalOrderBiz.selectByExample(example);
		List<Car> list=new ArrayList<>();
		for (int i = 0; i < findUidCar.size(); i++) {
			Car car=new Car();
			car.setP_id(findUidCar.get(i).getpId());
			car.setProduct_id(findUidCar.get(i).getProductId());
			Double price = DoubleUtil.div(Double.parseDouble(findUidCar.get(i).getTotalCommodityPrice()), Double.parseDouble(findUidCar.get(i).getProductNum()));
			car.setU_name(price.toString());
			car.setProduct_num(findUidCar.get(i).getProductNum());
			List<CommodityList> findcPhtoto=findcPhtoto(findUidCar.get(i).getProductId());
			for (int j = 0; j < findcPhtoto.size(); j++) {
				car.setPhtoto(findcPhtoto.get(j).getcPhtoto().split(",")[0]);
				car.setC_name(findcPhtoto.get(j).getcName());
				car.setC_describe(findcPhtoto.get(j).getcDescribe());
			}
			list.add(car);
		}
		new CallBack().yes(response, list, "");
	}
	/**
	 * @findcPhtoto
	 * @辅助方法查询图片
	 * @param cId
	 * @return
	 */
	public List<CommodityList> findcPhtoto(String cId) {
		CommodityList example=new CommodityList();
		example.setcId(cId);
		List<CommodityList> findcPhtoto=commodityListBiz.findcPhtoto(example);
		return findcPhtoto;
	}
	/**
	 * @方法名：updateShopCar
	 * @方法描述：个人购物车修改数量
	 * @param request
	 * @param response
	 */
	@RequestMapping("txr/updateShopCar")
	public void updataShopCar(HttpServletRequest request,HttpServletResponse response) {
	PersonalOrder record=new PersonalOrder();
		record.setProductNum(request.getParameter("ProductNum"));
		PersonalOrderExample example=new PersonalOrderExample();
		com.tszs.entity.PersonalOrderExample.Criteria ca=example.createCriteria();
		ca.andPIdEqualTo(request.getParameter("PId"));
		int size=personalOrderBiz.updateByExampleSelective(record, example);
		if(size>0) {
			new CallBack().yes(response, "", "");
		}else {
			new CallBack().no(response, "", "");
		}
	}
	/**
	 * @方法名：updatepstatic
	 * @方法描述：个人购物车伪删除
	 * @param request
	 * @param response
	 */
	@RequestMapping("txr/updatePstatic")
	public void updatePstatic(HttpServletRequest request,HttpServletResponse response) {
		String pId=request.getParameter("pId");
		PersonalOrderExample example=new PersonalOrderExample();
		com.tszs.entity.PersonalOrderExample.Criteria ca=example.createCriteria();
		List<String> list=new ArrayList<>();
		for (int i = 0; i <pId.split(",").length; i++) {
			list.add(pId.split(",")[i]);
		}
		System.out.println(list);
		ca.andPIdIn(list);
		int size=personalOrderBiz.deleteByExample(example);
		if(size>0) {
			new CallBack().yes(response, "", "");
		}else {
			new CallBack().no(response, "", "");
		}
	}
	/**
	 * @方法名：selectPayStatic0
	 * @方法描述：查询未付款
	 * @param request
	 * @param response
	 */
	@RequestMapping("txr/selectPayStatic0")
	public void selectPayStatic0(HttpServletRequest request,HttpServletResponse response) {
		List<PersonalOrder> selectByExample=selectByExample(request.getSession().getAttribute("openid")+"","1");
		List<Car> list=new ArrayList<>();
		for (int i = 0; i < selectByExample.size(); i++) {
			Car car=new Car();
			
			String total =  selectByExample.get(i).getTotalCommodityPrice();
			
			car.setP_id(selectByExample.get(i).getpId());
			car.setU_name(selectByExample.get(i).getuName());
			car.setCreatetime(selectByExample.get(i).getpCreateTime());
			car.setProduct_num(selectByExample.get(i).getProductNum());
			List<CommodityList> findcPhtoto=findcPhtoto(selectByExample.get(i).getProductId());
			for (int j = 0; j < findcPhtoto.size(); j++) {
				System.out.println(findcPhtoto.get(j).getcPhtoto().split(",")[0]);
				car.setPhtoto(findcPhtoto.get(j).getcPhtoto().split(",")[0]);
				car.setC_name(findcPhtoto.get(j).getcName());
				car.setC_describe(findcPhtoto.get(j).getcDescribe());
				
				car.setHref(total+"--"+"取消订单"+"--"+"付款");
			}
			list.add(car);
		}
		if(list.size()>0) {
			new CallBack().yes(response, list, "");
			
		}else {
			new CallBack().no(response, "", "");
		}
	}
	/**
	 * @方法名：ysh
	 * @方法描述：查询已经收到的货物
	 * @param request
	 * @param response
	 */
	@RequestMapping("txr/ysh")
	public void ysh(HttpServletRequest request,HttpServletResponse response) {
		PersonalOrderExample example=new PersonalOrderExample();
		com.tszs.entity.PersonalOrderExample.Criteria ca=example.createCriteria();
		ca.andUIdEqualTo(request.getSession().getAttribute("openid")+"");
		ca.andPStaticEqualTo("1");
		ca.andRoutinStatusEqualTo("3");
		List<PersonalOrder> selectByExample=personalOrderBiz.selectByExample(example);
		List<Car> list=new ArrayList<>();
		for (int i = 0; i < selectByExample.size(); i++) {
			Car car=new Car();
			car.setP_id(selectByExample.get(i).getpId());
			car.setU_name(selectByExample.get(i).getuName());
			car.setCreatetime(selectByExample.get(i).getpCreateTime());
			car.setProduct_num(selectByExample.get(i).getProductNum());
			List<CommodityList> findcPhtoto=findcPhtoto(selectByExample.get(i).getProductId());
			for (int j = 0; j < findcPhtoto.size(); j++) {
				car.setPhtoto(findcPhtoto.get(j).getcPhtoto().split(",")[0]);
				car.setC_name(findcPhtoto.get(j).getcName());
				car.setC_describe(findcPhtoto.get(j).getcDescribe());
				car.setHref("删除订单"+"--"+"查看订单");
			}
			list.add(car);
		}
		new CallBack().yes(response, list, "");
	}
	/**
	 * @方法名：routin_status
	 * @方法描述：查询待收货物
	 * @param request
	 * @param response
	 */
	@RequestMapping("txr/routin_status")
	public void routin_status(HttpServletRequest request,HttpServletResponse response) {
		List<PersonalOrder> selectByExample=selectByExample(request.getSession().getAttribute("openid")+"","2");
		List<Car> list=new ArrayList<>();
		for (int i = 0; i < selectByExample.size(); i++) {
			Car car=new Car();
			car.setP_id(selectByExample.get(i).getpId());
			String total =  selectByExample.get(i).getTotalCommodityPrice();
			
			car.setU_name(selectByExample.get(i).getuName());
			car.setCreatetime(selectByExample.get(i).getpCreateTime());
			car.setProduct_num(selectByExample.get(i).getProductNum());
			List<CommodityList> findcPhtoto=findcPhtoto(selectByExample.get(i).getProductId());
			for (int j = 0; j < findcPhtoto.size(); j++) {
				car.setPhtoto(findcPhtoto.get(j).getcPhtoto().split(",")[0]);
				car.setC_name(findcPhtoto.get(j).getcName());
				car.setC_describe(findcPhtoto.get(j).getcDescribe());
				car.setHref(total+"--"+"确认收货"+"--"+"查看物流");
			}
			list.add(car);
		}
		new CallBack().yes(response, list, "");
	}
	/**
	 * @方法名：pjxiangqing
	 * @方法描述：评价详情
	 * @param request
	 * @param response
	 */
	@RequestMapping("txr/pjxiangqing")
	public void pjxiangqing(HttpServletRequest request,HttpServletResponse response) {
		PersonalOrder example=new PersonalOrder();
		example.setuId(request.getSession().getAttribute("openid")+"");
		List<PersonalOrder> selectByExample=personalOrderBiz.queryComment(example);
		List<Car> list=new ArrayList<>();
		for (int i = 0; i < selectByExample.size(); i++) {
			PersonalOrder order = selectByExample.get(i);
			Car car=new Car();
			car.setP_id(order.getpId());
			car.setCreatetime(order.getpCreateTime());
			car.setPhtoto(order.getPhtoto());
			car.setC_name(order.getGoodsName());
			car.setHref("查看评价"+"--");
			car.setMcontent(order.getmContent());
			list.add(car);
		}
		new CallBack().yes(response, list, "");
	}
	/**
	 * @方法名：pj
	 * @方法描述：查询评价 未评价
	 * @param request
	 * @param response
	 */
	@RequestMapping("txr/pj")
	public void pj(HttpServletRequest request,HttpServletResponse response) {
		PersonalOrderExample example=new PersonalOrderExample();
		com.tszs.entity.PersonalOrderExample.Criteria ca=example.createCriteria();
		ca.andUIdEqualTo(request.getSession().getAttribute("openid")+"");
		ca.andPStaticEqualTo("1");
		ca.andPayStaticEqualTo("1");
		ca.andPjEqualTo("0");
		ca.andRoutinStatusEqualTo("3");
		List<PersonalOrder> selectByExample=personalOrderBiz.selectByExample(example);
		List<Car> list=new ArrayList<>();
		for (int i = 0; i < selectByExample.size(); i++) {
			Car car=new Car();
			car.setP_id(selectByExample.get(i).getpId());
			car.setCreatetime(selectByExample.get(i).getpCreateTime());
			List<CommodityList> findcPhtoto=findcPhtoto(selectByExample.get(i).getProductId());
			for (int j = 0; j < findcPhtoto.size(); j++) {
				car.setPhtoto(findcPhtoto.get(j).getcPhtoto().split(",")[0]);
				car.setC_name(findcPhtoto.get(j).getcName());
				car.setC_describe(findcPhtoto.get(j).getcDescribe());
				car.setHref("评论");
			}
			list.add(car);
		}
		new CallBack().yes(response, list, "");
	}
	/**
	 * @方法名：mul
	 * @方法描述：乘法
	 * @param num
	 * @param price
	 * @return
	 */
    public static Double mul(String num, String price){        // 进行乘法运算
         BigDecimal b1 = new BigDecimal(num);
         BigDecimal b2 = new BigDecimal(price);
        DecimalFormat df1 = new DecimalFormat();
        String str = df1.format(b1.multiply(b2).doubleValue());
        Double d=Double.parseDouble(str.replaceAll(",", ""));
		return d;
     }
	/**
	 * @方法名：selectByExample
	 * @方法描述：查询 
	 * @param type 类型数据标注
	 * @param openid 个人ID——openid
	 * @return
	 */
	public List<PersonalOrder> selectByExample(String openid,String type) {
		PersonalOrderExample example=new PersonalOrderExample();
		com.tszs.entity.PersonalOrderExample.Criteria ca=example.createCriteria();
		ca.andUIdEqualTo(openid);
		//订单都是1
		ca.andPStaticEqualTo("1");
		if(type.equals("1")) {
			//待付款订单
			ca.andPayStaticEqualTo("0");//System.out.println("查询待付款商品");
		}else if(type.equals("2"))  {
			//待收货货物
			ca.andRoutinStatusBetween("1", "2");
		}else {
			ca.andPjEqualTo("0");
		}
		List<PersonalOrder> selectByExample=personalOrderBiz.selectByExample(example);
		return selectByExample;
	}
	/***
	 * @方法名：confirmationOfOrder
	 * @方法描述：订单确认页面 商品描述 数量总价等展示
	 * @param request
	 * @param response
	 */
	@RequestMapping("txr/confirmationOfOrder")
	public void confirmationOfOrder(HttpServletRequest request,HttpServletResponse response) {
		PersonalOrder example=new PersonalOrder();
		example.setuId(request.getSession().getAttribute("openid")+"");
		String pid=request.getParameter("pid");
		List<String> list=new ArrayList<>();
		for (int i = 0; i < pid.split(",").length; i++) {
			if(pid.split(",")[i].equals("on")) {
			}else {
				list.add(pid.split(",")[i]);
			}
		}
		PersonalOrderExample examplePersonal=new PersonalOrderExample();
		com.tszs.entity.PersonalOrderExample.Criteria ca=examplePersonal.createCriteria();
		ca.andPIdIn(list);
		ca.andUIdEqualTo(request.getSession().getAttribute("openid")+"");
		//ca.andPStaticEqualTo("0");
		ca.andPayStaticEqualTo("0");
		List<PersonalOrder> confirmationOfOrder=personalOrderBiz.selectByExample(examplePersonal);
		List<PersonalOrder> list1=new ArrayList<>();
		
		List<String > lists=new ArrayList<>();
		for (int i = 0; i < confirmationOfOrder.size(); i++) {
			PersonalOrder personalOrder=new PersonalOrder();
			personalOrder.setpId(confirmationOfOrder.get(i).getpId());
			personalOrder.setProductNum(confirmationOfOrder.get(i).getProductNum());
			personalOrder.setpCreateTime(confirmationOfOrder.get(i).getpCreateTime());
			Double price = DoubleUtil.div(Double.parseDouble(confirmationOfOrder.get(i).getTotalCommodityPrice()), Double.parseDouble(confirmationOfOrder.get(i).getProductNum()));
			personalOrder.setuName(price.toString());
			
			List<CommodityList> findcPhtoto=findcPhtoto(confirmationOfOrder.get(i).getProductId());
			lists.add(confirmationOfOrder.get(i).getTotalCommodityPrice());
			for (int j = 0; j < findcPhtoto.size(); j++) {
				personalOrder.setBegin(findcPhtoto.get(j).getcPhtoto().split(",")[0]);//商品图片
				personalOrder.setEnd(findcPhtoto.get(j).getcName());//名称
				personalOrder.setTradeno(findcPhtoto.get(j).getcDescribe());//描述
		
			}
			list1.add(personalOrder);
		}
		System.out.println("所有价格综合："+lists);
		BigDecimal f = new BigDecimal("0");
		for (String string : lists) {
			f=f.add(new BigDecimal(string));
		}
		System.err.println("总价："+f);//=110.59
		Map<String, Object> map=new HashMap<>();
		map.put("Total", f);
		map.put("datas", list1);
		List<Map<String, Object>> listcallback=new 	ArrayList<>();
		listcallback.add(map);
		if(list1.size()>0) {
			new CallBack().yes(response, listcallback, "");
		}else {
			new CallBack().no(response, "", "");
		}
	}
	
	
	/**
	 * @方法名：pjshopdatails
	 * @方法描述：查询评价 未评价
	 * @param request
	 * @param response
	 */
	@RequestMapping("txr/pjshopdatails")
	public void pjshopdatails(HttpServletRequest request,HttpServletResponse response) {
		PersonalOrderExample example=new PersonalOrderExample();
		com.tszs.entity.PersonalOrderExample.Criteria ca=example.createCriteria();
		ca.andPIdEqualTo(request.getParameter("pId"));
		List<PersonalOrder> selectByExample=personalOrderBiz.selectByExample(example);
		List<Car> list=new ArrayList<>();
		for (int i = 0; i < selectByExample.size(); i++) {
			Car car=new Car();
			car.setP_id(selectByExample.get(i).getpId());
			car.setProduct_id(selectByExample.get(i).getProductId());
			car.setU_name(selectByExample.get(i).getuName());
			List<CommodityList> findcPhtoto=findcPhtoto(selectByExample.get(i).getProductId());
			for (int j = 0; j < findcPhtoto.size(); j++) {
				car.setPhtoto(findcPhtoto.get(j).getcPhtoto().split(",")[0]);
				car.setC_name(findcPhtoto.get(j).getcName());
				car.setC_describe(findcPhtoto.get(j).getcDescribe());
			}
			list.add(car);
		}
		new CallBack().yes(response, list, "");
	}
	
	
	/***
	 * 确认收货 修改订单状态，检查是否有分销人以及是否卖出的是分销产品，进行分销
	 * @author MRC
	 * @date 2019年5月31日上午9:31:45
	 * @param request
	 * @param response
	 */
	@RequestMapping("txr/confirmOrder")
	public void confirmOrder(HttpServletRequest request,HttpServletResponse response) {
		
		PersonalOrderExample example=new PersonalOrderExample();
		com.tszs.entity.PersonalOrderExample.Criteria ca=example.createCriteria();
		
		ca.andPIdEqualTo(request.getParameter("pId"));
		
		List<PersonalOrder> selectByExample=personalOrderBiz.selectByExample(example);
		
		if (selectByExample.size() == 1) {
			//存在订单
			PersonalOrder record=new PersonalOrder();
			record.setRoutinStatus("3");//确认收货
			record.setPj("0");//未评价
			personalOrderBiz.updateByExampleSelective(record, example);
			PersonalOrder order = selectByExample.get(0);
			if (StringUtils.isNotEmpty(order.getdDistributionidentification())) {
				//分销开始
				personalOrderBiz.orderDistribution(order);
			}
		} else {
			
			new CallBack().no(response, "", "订单信息错误！");
		}
	}
	
	/**
	 * 线下支付
	 * @author Fujing
	 * @date 2019年6月1日 上午10:56:36
	 * @param request
	 * @param response void
	 */
	@RequestMapping("txr/offlinePay")
	public void offlinePay(HttpServletRequest request, HttpServletResponse response) {
		String pId = request.getParameter("pId");
		if(StringUtils.isEmpty(pId)) {
			new CallBack().no(response, "", "订单信息错误！");
		}
		PersonalOrderExample example=new PersonalOrderExample();
		com.tszs.entity.PersonalOrderExample.Criteria ca=example.createCriteria();
		
		ca.andPIdEqualTo(request.getParameter("pId"));
		
		List<PersonalOrder> selectByExample=personalOrderBiz.selectByExample(example);
		
		if(selectByExample.size() == 1) {
			//存在订单
			PersonalOrder record=new PersonalOrder();
			record.setRoutinStatus("1");//待付款
			record.setPj("0");//未评价
			record.setpStatic("0");//线下支付
			record.setpStatic("1");//变为订单
			personalOrderBiz.updateByExampleSelective(record, example);
			new CallBack().yes(response, "", "");
		} else {
			new CallBack().no(response, "", "订单信息错误！");
		}
	}
	
	
}
